package h0830;

import java.util.Arrays;

public class QuickSort {
    public static void main(String[] args) {
        int[] nums = {4,3,2,1};
        fastSort(nums, 0, nums.length - 1);
        System.out.println(Arrays.toString(nums));
    }

    private static void fastSort(int[] nums, int left, int right) {
        if (left < right) {
            int p = partition(nums, left, right);
            fastSort(nums, left, p - 1);
            fastSort(nums, p + 1, right);
        }
    }

    private static int partition(int[] nums, int left, int right) {
        //选择最左边元素为基准元素
        int pivot = nums[left];
        //这个是从left+1开始
        int i = left + 1;
        int j = right;
        while (i <= j) {
            while (i <= right && nums[i] <= pivot) {
                i++;
            }
            while (j >= left && nums[j] > pivot) {
                j--;
            }
            if (i<j){
                swap(nums, i, j);
            }
        }
        swap(nums, left, j);
        return j;
    }

    private static void swap(int[] nums, int i, int j) {
        int temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }
}
